#usage:
#	makebin appname directory
#
if [ $# -ne 2 ]; then
    	echo usage: makebin package directory
    	echo example: ./makebin tunnel.bin tunnel
	exit
fi

#
# find the directory where makebin reside
n=`which $0`
d=`dirname $n`

BINPKG=$1
TMPPKG=${BINPKG}.tgz
SRCDIR=$2
SCRIPT=$d/install-template.sh

echo -n "looking for $SCRIPT ... "
if [ ! -e ${SCRIPT} ]; then
    echo "can't find ${SCRIPT}"
    exit 1
fi
echo " OK !"

#
# 1. clean working directory
if [ -e ${BINPKG} ]; then
    echo -n "removing old package ... "
    rm ${BINPKG}
    echo " OK!"
fi

#
# 2. packaging installation source
#
echo -n "packaging installation files ... "

tar cvzf ${TMPPKG} -C ${SRCDIR} . > /dev/null
if [ $? -ne 0 ]; then
    echo " Failed!"
    exit 1;
fi
echo " OK!"


# 3. making bin file
# get the number of line of the script
SCRIPT_LEN=`wc -l $SCRIPT | awk '{print $1}'`
SCRIPT_LEN=$((SCRIPT_LEN+1))
if [ -x /usr/bin/sum ] ; then
    #echo "Checksumming..."

    # calculate the checksum of the package
    sum=`/usr/bin/sum ${TMPPKG}`
    index=1
    
    #
    # sum returns two lines,¡¡assign them to sum1 and sum2 seperately
    #
    for s in $sum
    do
        case $index in
        1)  sum1=$s;
            index=2;
            ;;
        2)  sum2=$s;
            index=3;
            ;;
        esac
    done
    
    cat $SCRIPT | sed -e "s/#CHKSUM1#/$sum1/g" -e "s/#CHKSUM2#/$sum2/g" -e "s/#SCRIPT_LEN#/$SCRIPT_LEN/g" > \
		$BINPKG && cat -u ${TMPPKG} >> $BINPKG
    chmod 755 $BINPKG
    
    # echo "Finished"
else
    echo "Can't find /usr/bin/sum to do checksum.  Continuing anyway."
fi

#
# 4.  remove temporary file
#
echo -n "removing temporary package ... "
rm ${TMPPKG}
if [ $? -ne 0 ]; then
    echo " Failed!";
fi
echo " OK!"
echo "installaction package is created successfully! location=${BINPKG}"
